/*
 * @Author: your name
 * @Date: 2020-10-22 17:59:38
 * @LastEditTime: 2020-12-16 16:59:28
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \tlwok-filing-saas-front\src\lib\http.js
 */
import axios from './axios'
import { formatObjectEmpty, object2QueryStr } from './utils'
import { Message } from 'element-ui'
const API = axios.defaults.baseURL + 'api'

const Http = {
  getUrl (url) {
    // console.log(API, url)
    if (url.indexOf('/') !== 0) {
      url = '/' + url
    }
    return API + url
  },
  async request (url, data, method = 'get') {
    data = formatObjectEmpty(data)
    // console.log('url-data', url, data)
    const response = await axios({
      method,
      url: Http.getUrl(url),
      data,
    })
    if (response.success) {
      return response.result
    } else {
      Message.error(response.desc)
      const error = new Error(response.desc)
      error.response = response
      throw error
    }
  },
  get (url, data = {}) {
    const queryStr = object2QueryStr(data)
    if (queryStr) {
      url += (url.indexOf('?') > -1 ? '&' : '?') + queryStr
    }
    return Http.request(url, null, 'get')
  },
  post (url, data = {}) {
    return Http.request(url, data, 'post')
  },
}

export default Http
